from PIL import Image, ImageDraw
import os


def mm_to_pixels(mm: float, resolution_m_per_pixel: float) -> int:
    """Convert millimeters to pixels given resolution in meters/pixel."""
    return int(round((mm / 1000.0) / resolution_m_per_pixel))


def draw_free_area_with_border(width_mm: int, height_mm: int, resolution_m_per_pixel: float,
                               border_width_pixels: int, output_filename: str) -> None:
    """
    依据给定的物理尺寸与分辨率，生成一个白色自由区域，四周用黑色边框包围，保存为PGM。

    width_mm:  自由区域宽度（毫米）
    height_mm: 自由区域高度（毫米）
    resolution_m_per_pixel: 地图分辨率（米/像素）
    border_width_pixels: 边框宽度（像素）
    output_filename: 输出PGM路径
    """

    width_m = width_mm / 1000.0
    height_m = height_mm / 1000.0

    # 自由区域像素尺寸
    free_width_pixels = int(round(width_m / resolution_m_per_pixel))
    free_height_pixels = int(round(height_m / resolution_m_per_pixel))

    # 总图像像素尺寸 = 自由区 + 两侧边框
    width_pixels = free_width_pixels + 2 * border_width_pixels
    height_pixels = free_height_pixels + 2 * border_width_pixels

    print(f"自由区(米): {width_m} x {height_m}")
    print(f"分辨率: {resolution_m_per_pixel} m/px")
    print(f"自由区(像素): {free_width_pixels} x {free_height_pixels}")
    print(f"整图尺寸(像素): {width_pixels} x {height_pixels}，边框: {border_width_pixels}px")

    # 背景黑色（障碍物），中间填充白色（自由区）
    img = Image.new('L', (width_pixels, height_pixels), color=0)
    draw = ImageDraw.Draw(img)

    free_left = border_width_pixels
    free_top = border_width_pixels
    free_right = free_left + free_width_pixels - 1
    free_bottom = free_top + free_height_pixels - 1
    draw.rectangle([(free_left, free_top), (free_right, free_bottom)], fill=255)

    img.save(output_filename)
    print(f"地图已保存: {output_filename}")


if __name__ == "__main__":
    # 自由空间为 5m (高) x 9m (宽)
    width_mm = 9000
    height_mm = 5000

    resolution = 0.05
    border_px = 5

    script_dir = os.path.dirname(os.path.abspath(__file__))
    out_file = os.path.join(script_dir, "area59.pgm")

    draw_free_area_with_border(width_mm, height_mm, resolution, border_px, out_file)


